import React, { useState } from "react";
import {
  Badge,
  Button,
  ButtonGroup,
  Select,
  LegacyStack,
  Collapsible,
  TextContainer,
  Link,
  Popover,
  ActionList,
  Modal,
  ChoiceList,
  AccountConnection,
  Combobox,
  ResourceList,
  ResourceItem,
  Text,
  Thumbnail,
  Icon,
  LegacyCard,
  TextField,
  Listbox,
  AutoSelection,
  Scrollable,
  EmptySearchResult,
} from "@shopify/polaris";
import {
  SearchMinor,
  MobileBackArrowMajor,
  ChevronLeftMinor,
  ChevronRightMinor,
  MobileVerticalDotsMajor,
  CalendarTimeMinor,
  InfoMinor,
  TemplateMajor,
  AddMajor,
  DragHandleMinor,
  ArrowLeftMinor,
} from "@shopify/polaris-icons";
import { useEffect } from "react";
import styled from "./index.module.less";
import { useCallback } from "react";

function ListboxWithSearchExample() {
  const [showTextF, setShowTextF] = useState(false);
  const actionValue = "__ACTION__";

  const [segments, setSegments] = useState([
    {
      label: "All customers",
      id: "gid://shopify/CustomerSegment/1",
      value: "0",
      children: true,
    },
    {
      label: "VIP customers",
      id: "gid://shopify/CustomerSegment/2",
      value: "1",
      children: false,
    },
    {
      label: "New customers",
      id: "gid://shopify/CustomerSegment/3",
      value: "2",
      children: true,
    },
    {
      label: "Abandoned carts - last 30 days",
      id: "gid://shopify/CustomerSegment/4",
      value: "3",
      children: false,
    },
    {
      label: "Wholesale customers",
      id: "gid://shopify/CustomerSegment/5",
      value: "4",
      children: false,
    },
    {
      label: "Email subscribers",
      id: "gid://shopify/CustomerSegment/6",
      value: "5",
      children: true,
    },
    {
      label: "From New York",
      id: "gid://shopify/CustomerSegment/7",
      value: "6",
      children: true,
    },
    {
      label: "Repeat buyers",
      id: "gid://shopify/CustomerSegment/8",
      value: "7",
      children: true,
    },
    {
      label: "First time buyers",
      id: "gid://shopify/CustomerSegment/9",
      value: "8",
      children: true,
    },
    {
      label: "From Canada",
      id: "gid://shopify/CustomerSegment/10",
      value: "9",
      children: true,
    },
    {
      label: "Bought in last 60 days",
      id: "gid://shopify/CustomerSegment/11",
      value: "10",
      children: true,
    },
    {
      label: "Bought last BFCM",
      id: "gid://shopify/CustomerSegment/12",
      value: "11",
      children: true,
    },
  ]);

  const [showcontent, setShowContent] = useState("假发");
  const [show, setShow] = useState(false);

  const [showFooterAction, setShowFooterAction] = useState(true);
  const [query, setQuery] = useState<string>("");
  const [lazyLoading, setLazyLoading] = useState(false);
  const [willLoadMoreResults, setWillLoadMoreResults] = useState(true);
  const [visibleOptionIndex, setVisibleOptionIndex] = useState(6);
  const [activeOptionId, setActiveOptionId] = useState(segments[0].id);
  const [selectedSegmentIndex, setSelectedSegmentIndex] = useState(0);
  const [filteredSegments, setFilteredSegments] = useState<
    (typeof segments)[number][]
  >([]);

  const handleClickShowAll = () => {
    setShowFooterAction(false);
    setVisibleOptionIndex(segments.length);
  };

  const handleFilterSegments = (query: any) => {
    const nextFilteredSegments = segments.filter((segment) => {
      return segment.label
        .toLocaleLowerCase()
        .includes(query.toLocaleLowerCase().trim());
    });

    setFilteredSegments(nextFilteredSegments);
  };

  const handleQueryChange = (query: any) => {
    setQuery(query);

    if (query.length >= 2) handleFilterSegments(query);
  };

  const handleQueryClear = () => {
    handleQueryChange("");
  };

  const handleSegmentSelect = (segmentIndex: string) => {
    console.log(segmentIndex);
    console.log(actionValue);

    if (Number(segmentIndex) + 1) {
      //   setChanpin(segments[Number(_) + 1 - 1].label);
      // setChanpin(segments[Number(segmentIndex) + 1 - 1].label);
      segments.forEach((item) => {
        if (item.value == segmentIndex) {
          setShowTextF(false);
          setChanpin(item.label);
        }
      });
    }

    if (segmentIndex === actionValue) {
      // console.log(666);

      setShowContent("全部");
      setShow(true);
      return handleClickShowAll();
    }

    setSelectedSegmentIndex(Number(segmentIndex));
  };

  const handleActiveOptionChange = (_: string, domId: string) => {
    setActiveOptionId(domId);
    // console.log("_", _);
    // console.log("domId", domId);
    // console.log("number", Number(_) + 1);
    // console.log("segments", segments[Number(_ + 1) - 1].label);
  };

  const listboxId = "SearchableListbox";

  const segmentOptions = query ? filteredSegments : segments;

  const segmentList =
    segmentOptions.length > 0
      ? segmentOptions
          .slice(0, visibleOptionIndex)
          .map(({ label, id, value, children }) => {
            const selected = segments[selectedSegmentIndex].value === value;

            return (
              <div key={id} className={styled.contents}>
                <div className={styled.CLEFT}>
                  <Listbox.Option key={id} value={value} selected={selected}>
                    <Listbox.TextOption selected={selected}>
                      <div className={styled.ellsp}>{label}</div>
                    </Listbox.TextOption>
                  </Listbox.Option>
                </div>
                {children && (
                  <div className={styled.btnCHildren}>
                    <div
                      className={styled.BTN}
                      onClick={(id) => {
                        handlechangesegments(id, label);
                      }}
                    >
                      <Icon source={ChevronRightMinor}></Icon>
                    </div>
                  </div>
                )}
              </div>
            );
          })
      : null;

  const showAllMarkup = showFooterAction ? (
    <Listbox.Action value={actionValue}>
      <span style={{ color: "var(--p-color-text-interactive)" }}>全部浏览</span>
    </Listbox.Action>
  ) : null;

  const lazyLoadingMarkup = lazyLoading ? (
    <Listbox.Loading
      accessibilityLabel={`${
        query ? "Filtering" : "Loading"
      } customer segments`}
    />
  ) : null;

  const noResultsMarkup =
    segmentOptions.length === 0 ? (
      <EmptySearchResult
        title=""
        description={`No segments found matching "${query}"`}
      />
    ) : null;

  const listboxMarkup = (
    <Listbox
      enableKeyboardControl
      autoSelection={AutoSelection.FirstSelected}
      accessibilityLabel="Search for and select a customer segment"
      customListId={listboxId}
      onSelect={handleSegmentSelect}
      onActiveOptionChange={handleActiveOptionChange}
    >
      {segmentList}
      {segments.length > 10 && showAllMarkup}
      {/* {showAllMarkup} */}
      {noResultsMarkup}
      {lazyLoadingMarkup}
    </Listbox>
  );

  const [popoverActive, setPopoverActive] = useState(false);

  const togglePopoverActive = useCallback(
    () => setPopoverActive((popoverActive) => !popoverActive),
    []
  );

  const [chanpin, setChanpin] = useState("");

  const handlechanpinChange = useCallback(
    (newValue: string) => setChanpin(newValue),
    []
  );

  const activator = (
    <div onClick={togglePopoverActive}>
      {showTextF && (
        <TextField label="" onChange={handlechanpinChange} autoComplete="off" />
      )}
      {!showTextF && (
        <TextField
          label=""
          value={chanpin}
          onChange={handlechanpinChange}
          autoComplete="off"
        />
      )}
    </div>
  );

  const handlechangesegments = (id: any, label: any) => {
    setShow(true);
    handleClickShowAll();
    setShowContent(label);
    // console.log(6666);
    setShowTextF(true);
    //保存父请求数据的标识

    //请求children
    setSegments([
      {
        label: "All customers11",
        id: "gid://shopify/CustomerSegment/99",
        value: "0",
        children: false,
      },
      {
        label: "All customers12",
        id: "gid://shopify/CustomerSegment/100",
        value: "1",
        children: false,
      },
    ]);
    // setChanpin(segments[0].label);
  };

  return (
    <Popover
      active={popoverActive}
      activator={activator}
      autofocusTarget="first-node"
      onClose={togglePopoverActive}
    >
      {/* <Popover.Pane fixed>
        <ActionList
          // actionRole="menuitem"
          items={[
            {
              content: "全部",
              onAction: () => {
                setChanpin("Online store");
              },
              prefix: <Icon source={ArrowLeftMinor}></Icon>,
            },
          ]}
        />
      </Popover.Pane>
      <Popover.Pane>
        <ActionList
          actionRole="menuitem"
          items={[
            {
              content: "动物/宠物用品",
              onAction: () => {
                setChanpin("动物/宠物用品");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
              // ariaHaspopup : "tree",
            },
            {
              content: "服饰与配饰",
              onAction: () => {
                setChanpin("服饰与配饰");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "艺术与娱乐",
              onAction: () => {
                setChanpin("艺术与娱乐");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "婴儿用品",
              onAction: () => {
                setChanpin("婴儿用品");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "商业/工业",
              onAction: () => {
                setChanpin("商业/工业");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "相机与光学器件",
              onAction: () => {
                setChanpin("相机与光学器件");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "电子产品",
              onAction: () => {
                setChanpin("电子产品");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "饮食/烟酒",
              onAction: () => {
                setChanpin("饮食/烟酒");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "家具",
              onAction: () => {
                setChanpin("家具");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "五金/硬件",
              onAction: () => {
                setChanpin("五金/硬件");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "保健/美容/卫生/护理",
              onAction: () => {
                setChanpin("保健/美容/卫生/护理");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "家居与园艺",
              onAction: () => {
                setChanpin("家居与园艺");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "箱包",
              onAction: () => {
                setChanpin("箱包");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "成人",
              onAction: () => {
                setChanpin("成人");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "媒体",
              onAction: () => {
                setChanpin("媒体");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "办公用品",
              onAction: () => {
                setChanpin("办公用品");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "宗教/仪式",
              onAction: () => {
                setChanpin("宗教/仪式");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "软件",
              onAction: () => {
                setChanpin("软件");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "体育用品",
              onAction: () => {
                setChanpin("体育用品");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "玩具/游戏",
              onAction: () => {
                setChanpin("玩具/游戏");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "交通工具/汽车/飞机/船舶",
              onAction: () => {
                setChanpin("交通工具/汽车/飞机/船舶");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
            {
              content: "礼品卡",
              onAction: () => {
                setChanpin("礼品卡");
              },
              suffix: (
                <div
                  className={styled.popoverButton}
                  onClick={() => {
                    console.log(6666);
                  }}
                >
                  <Icon source={ChevronRightMinor}></Icon>
                </div>
              ),
            },
          ]}
        />
      </Popover.Pane> */}

      <div
        style={{
          alignItems: "stretch",
          borderTop: "1px solid #DFE3E8",
          display: "flex",
          flexDirection: "column",
          justifyContent: "stretch",
          position: "relative",
          width: "100%",
          height: "100%",
          overflow: "hidden",
        }}
      >
        {/* {textFieldMarkup} */}
        <Scrollable
          shadow
          style={{
            position: "relative",
            height: "292px",
            padding: "var(--p-space-2) 0",
            borderBottomLeftRadius: "var(--p-border-radius-2)",
            borderBottomRightRadius: "var(--p-border-radius-2)",
          }}
          //   onScrolledToBottom={handleLazyLoadSegments}
        >
          {!show && (
            <div
              className={styled.FHSYJs}
              onClick={() => {
                setChanpin("假发");
              }}
            >
              <div>{showcontent}</div>
              <div className={styled.PPPP}>建议</div>
            </div>
          )}
          {show && (
            <div className={styled.FHSYJ}>
              {showcontent !== "全部" && (
                <div className={styled.iCON}>
                  <Icon source={MobileBackArrowMajor}></Icon>
                </div>
              )}
              <div
                className={styled.QB}
                onClick={() => {
                  if (showcontent == "全部") {
                  } else {
                    //模拟请求拿到数据
                    //更新segments
                    setSegments([
                      {
                        label: "All customers",
                        id: "gid://shopify/CustomerSegment/1",
                        value: "0",
                        children: true,
                      },
                      {
                        label: "VIP customers",
                        id: "gid://shopify/CustomerSegment/2",
                        value: "1",
                        children: false,
                      },
                      {
                        label: "New customers",
                        id: "gid://shopify/CustomerSegment/3",
                        value: "2",
                        children: true,
                      },
                      {
                        label: "Abandoned carts - last 30 days",
                        id: "gid://shopify/CustomerSegment/4",
                        value: "3",
                        children: false,
                      },
                      {
                        label: "Wholesale customers",
                        id: "gid://shopify/CustomerSegment/5",
                        value: "4",
                        children: false,
                      },
                      {
                        label: "Email subscribers",
                        id: "gid://shopify/CustomerSegment/6",
                        value: "5",
                        children: true,
                      },
                      {
                        label: "From New York",
                        id: "gid://shopify/CustomerSegment/7",
                        value: "6",
                        children: true,
                      },
                      {
                        label: "Repeat buyers",
                        id: "gid://shopify/CustomerSegment/8",
                        value: "7",
                        children: true,
                      },
                      {
                        label: "First time buyers",
                        id: "gid://shopify/CustomerSegment/9",
                        value: "8",
                        children: true,
                      },
                      {
                        label: "From Canada",
                        id: "gid://shopify/CustomerSegment/10",
                        value: "9",
                        children: true,
                      },
                      {
                        label: "Bought in last 60 days",
                        id: "gid://shopify/CustomerSegment/11",
                        value: "10",
                        children: true,
                      },
                      {
                        label: "Bought last BFCM",
                        id: "gid://shopify/CustomerSegment/12",
                        value: "11",
                        children: true,
                      },
                    ]);
                    setShowContent("全部");
                  }
                }}
              >
                {showcontent}
              </div>
            </div>
          )}
          {listboxMarkup}
        </Scrollable>
      </div>
    </Popover>
  );
}

export default ListboxWithSearchExample;
